package com.tofine.smarthome.adapter;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CompoundButton;
import android.widget.Toast;

import com.bignerdranch.expandablerecyclerview.Adapter.ExpandableRecyclerAdapter;
import com.bignerdranch.expandablerecyclerview.Model.ParentListItem;
import com.squareup.picasso.Picasso;
import com.tofine.smarthome.R;
import com.tofine.smarthome.model.Device;
import com.tofine.smarthome.model.Room;
import com.tofine.smarthome.rest.RestClient;
import com.tofine.smarthome.rest.model.Command;
import com.tofine.smarthome.ui.DeviceInfoActivity;
import com.tofine.smarthome.util.CommandUtils;

import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * @author ddMax
 * @since 2016/4/29 0:59.
 */
public class RoomRecyclerViewAdapter extends ExpandableRecyclerAdapter<RoomViewHolder, DeviceViewHolder> {

    private Context mContext;
    private List<? extends ParentListItem> mParentDataSet;

    public RoomRecyclerViewAdapter(Context context, @NonNull List<? extends ParentListItem> parentItemList) {
        super(parentItemList);
        this.mContext = context;
        this.mParentDataSet = parentItemList;
    }

    /**
     * 创建RoomViewHolder，作为父视图
     * @param parentViewGroup 对应的父视图
     * @return ViewHolder对象
     */
    @Override
    public RoomViewHolder onCreateParentViewHolder(ViewGroup parentViewGroup) {
        View view = LayoutInflater.from(mContext).inflate(R.layout.item_room, parentViewGroup, false);
        return new RoomViewHolder(view);
    }

    /**
     * 创建DeviceViewHolder，作为子视图
     * @param childViewGroup 对应的父视图
     * @return ViewHolder对象
     */
    @Override
    public DeviceViewHolder onCreateChildViewHolder(ViewGroup childViewGroup) {
        View view = LayoutInflater.from(mContext).inflate(R.layout.item_device_child, childViewGroup, false);
        return new DeviceViewHolder(view);
    }

    /**
     * 绑定RoomViewHolder的数据
     * @param holder 当前的ViewHolder实例
     * @param position ViewHolder实例的位置
     * @param parentListItem 对象
     */
    @Override
    public void onBindParentViewHolder(RoomViewHolder holder, int position, ParentListItem parentListItem) {
        final Room room = (Room) parentListItem;
        if (room.image == null) {
            holder.mRoomImage.setVisibility(View.GONE);
        } else {
            Picasso.with(mContext).load(Uri.parse(room.image)).into(holder.mRoomImage);
        }
        holder.mRoomTitle.setText(room.name);
        holder.mRoomAmount.setText(String.valueOf(room.devices().size()));
    }

    /**
     * 绑定DeviceViewHolder的数据
     * @param holder 当前的ViewHolder实例
     * @param position ViewHolder实例的位置
     * @param childListItem 对象
     */
    @Override
    public void onBindChildViewHolder(final DeviceViewHolder holder, int position, Object childListItem) {
        final Device device = (Device) childListItem;
        // 整个Item点击监听
        holder.mItem.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(mContext, DeviceInfoActivity.class);
                Bundle bundle = new Bundle();
                bundle.putSerializable("device", device);
                bundle.putInt("mode", DeviceInfoActivity.MODE_EDIT);
                intent.putExtras(bundle);
                mContext.startActivity(intent);
            }
        });
        // 设备图片
        Picasso.with(mContext).load(Uri.parse(device.image)).into(holder.mDeviceImage);
        // 设备名称
        holder.mDeviceTitle.setText(device.name);
        // 设备开关状态
        holder.mDeviceSwitch.setChecked(device.status);
        holder.mDeviceSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, final boolean isChecked) {
                device.status = isChecked;

                final ProgressDialog dialog = new ProgressDialog(mContext);
                dialog.setMessage("正在与设备通信");
                dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
                dialog.show();
                RestClient.getInstance().getApiService().sendCommand(device._id, CommandUtils.genCommand(device)).enqueue(new Callback<Command>() {
                    @Override
                    public void onResponse(Call<Command> call, Response<Command> response) {
                        dialog.cancel();
                        device.save();
                    }

                    @Override
                    public void onFailure(Call<Command> call, Throwable t) {

                        dialog.cancel();
                        device.save();
                        t.printStackTrace();
                    }
                });

            }
        });
        // 是否标记为收藏
        if (device.isFavorite) {
            setFavoriteIcon(holder, true);
            holder.favoriteView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    // 点击取消收藏
                    device.isFavorite = false;

                    RestClient.getInstance().getApiService().updateDevice(device._id, device).enqueue(new Callback<Device>() {
                        @Override
                        public void onResponse(Call<Device> call, Response<Device> response) {
                            device.save();
                            setFavoriteIcon(holder, false);
                            holder.swipeLayout.close(true);
                            Toast.makeText(mContext, "已取消收藏", Toast.LENGTH_SHORT).show();
                        }

                        @Override
                        public void onFailure(Call<Device> call, Throwable t) {
                            device.save();
                            setFavoriteIcon(holder, false);
                            holder.swipeLayout.close(true);
                            t.printStackTrace();
                        }
                    });

                }
            });
        } else {
            setFavoriteIcon(holder, false);
            holder.favoriteView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    // 点击收藏
                    device.isFavorite = true;
                    device.save();
                    setFavoriteIcon(holder, true);
                    holder.swipeLayout.close(true);
                    Toast.makeText(view.getContext(), "收藏成功！", Toast.LENGTH_SHORT).show();
                }
            });
        }
        holder.deleteView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new AlertDialog.Builder(mContext)
                        .setTitle(R.string.dialog_title)
                        .setMessage(String.format(mContext.getString(R.string.dialog_delete_device_confirm), device.name))
                        .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(final DialogInterface dialog, int which) {
                                // TODO: 子ViewHolder的删除后Adapter的刷新
                                device.delete();
//                                mItemManger.removeShownLayouts(holder.swipeLayout);
//                                mDataSet.remove(position);
//                                notifyChildItemRemoved(parentPosition, position);
//                                notifyChildItemRangeChanged(parentPosition, position, mParentDataSet.size());

                                RestClient.getInstance().getApiService().deleteDevice(device._id).enqueue(new Callback<Device>() {
                                    @Override
                                    public void onResponse(Call<Device> call, Response<Device> response) {
                                        dialog.dismiss();
                                    }

                                    @Override
                                    public void onFailure(Call<Device> call, Throwable t) {

                                    }
                                });

                            }
                        })
                        .setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.cancel();
                            }
                        })
                        .create()
                        .show();

            }
        });
    }

    private void setFavoriteIcon(final DeviceViewHolder holder, boolean isFavorite) {
        holder.favoriteView.setImageDrawable(ContextCompat.getDrawable(
                mContext, isFavorite ?
                        R.drawable.ic_favorite_white_24dp : R.drawable.ic_favorite_border_white_24dp
        ));
    }

}
